//
//  ForgetPWViewController.swift
//  FeastBooking
//
//  Created by Imon on 2017/12/11.
//  Copyright © 2017年 Imon. All rights reserved.
//

import UIKit
import RxSwift

class ForgetPWViewController: UIViewController, UITextFieldDelegate {
    
    let userAuthVM = UserAuthViewModel.shared
    
    let disposeBag = DisposeBag()
    
    var showLoginView: ((_ sender: UIViewController) -> Void)?
    
    let verifyCodeLength: Int = 6
    
    var toWaitSec: Int = 0
    
    var timer: Timer = Timer()
    
    @IBOutlet weak var button: UIButton!
        
    @IBOutlet weak var topLayoutConstraint: NSLayoutConstraint!
    
    let closeButton: UIButton = {
        let button = UIButton()
        button.setImage(UIImage(named: "cross"), for: .normal)
        return button
    }()
    
    let titleLabel: UILabel = {
        let label = UILabel()
        label.font = AppFont(size: 25)
        label.textColor = UIColor.gray
        label.text = LanguageHelper.getString(key: "VERIFY_EMAIL")
        return label
    }()
    
    let descriptionLabel: UILabel = {
        let label = UILabel()
        label.font = AppFont(size: 14)
        label.textColor = lightTextColor
        label.text = LanguageHelper.getString(key: "VERIFY_TO_RESET")
        return label
    }()
    
    let emailTextField: UITextField = {
        let textField = UITextField()
        textField.placeholder = LanguageHelper.getString(key: "EMAIL")
        textField.font = AppFont(size: 15)
        return textField
    }()
    
    let verifyTextField: UITextField = {
        let textField = UITextField()
        textField.placeholder = LanguageHelper.getString(key: "VERIFY_CODE")
        textField.font = AppFont(size: 15)
        textField.keyboardType = .numberPad
        return textField
    }()
    
    let getVerifyButton: UIButton = {
        let button = UIButton()
        button.layer.borderColor = UIColor.lightGray.cgColor
        button.backgroundColor = lightSaperatorColor
        button.layer.borderWidth = 1
        button.layer.cornerRadius = 3
        button.setTitle(LanguageHelper.getString(key: "GET_VERIFY_CODE"), for: .normal)
        button.setTitleColor(UIColor.gray, for: .normal)
        button.titleLabel?.font = AppFont(size: 13)
        return button
    }()
    
    let verifySaperator: UIView = {
        let view = UIView()
        view.backgroundColor = saperatorColor
        return view
    }()
    
    let emailSaperator: UIView = {
        let view = UIView()
        view.backgroundColor = saperatorColor
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        
        button.layer.cornerRadius = 3
        button.layer.masksToBounds = true
        
        closeButton.frame = CGRect(x: 5, y: 5, width: 25, height: 25)
        closeButton.addTarget(self, action: #selector(close(_:)), for: .touchUpInside)
        
        closeButton.frame = CGRect(x: 15, y: 35, width: 22, height: 22)
        closeButton.addTarget(self, action: #selector(close(_:)), for: .touchUpInside)
        
        let leading: CGFloat = 45
        
        let textMaxSize = CGSize(width: self.view.bounds.width, height: 30)
        let titleSize = TextSize.textSize(text: titleLabel.text!, font: titleLabel.font, maxSize: textMaxSize)
        titleLabel.frame = CGRect(x: leading, y: 85, width: titleSize.width, height: titleSize.height)
        let descriptionSize = TextSize.textSize(text: descriptionLabel.text!, font: descriptionLabel.font, maxSize: textMaxSize)
        descriptionLabel.frame = CGRect(x: leading, y: titleLabel.frame.origin.y + titleLabel.frame.height + 8, width: descriptionSize.width, height: descriptionSize.height)
        
        var currentY = descriptionLabel.frame.origin.y + descriptionLabel.frame.height
        
        emailTextField.frame = CGRect(x: leading, y: currentY + 30, width: self.view.bounds.width - CGFloat(2) * leading, height: 25)
        
        currentY = emailTextField.frame.origin.y + emailTextField.frame.height
        
        emailSaperator.frame = CGRect(x: leading, y: currentY + 8, width: self.view.bounds.width - CGFloat(2) * leading, height: 0.5)
        
        currentY = emailSaperator.frame.origin.y + emailSaperator.frame.height
        
        verifyTextField.frame = CGRect(x: leading, y: currentY + 30, width: (self.view.bounds.width - CGFloat(2) * leading) / 2, height: 25)
        
        let gvButtonGap: CGFloat = 5
        
        getVerifyButton.frame = CGRect(x: verifyTextField.frame.origin.x + verifyTextField.frame.width + gvButtonGap, y: currentY + 25, width: (self.view.bounds.width - CGFloat(2) * leading) / 2 - gvButtonGap, height: 38)
        
        currentY = verifyTextField.frame.origin.y + verifyTextField.frame.height
        
        verifySaperator.frame = CGRect(x: leading, y: currentY + 8, width: (self.view.bounds.width - CGFloat(2) * leading) / 2, height: 0.5)
        
        currentY = verifySaperator.frame.origin.y + verifySaperator.frame.height
        
        topLayoutConstraint.constant = currentY + 45
        
        currentY = currentY + 45 + button.frame.height
        
        currentY += 20
        
        getVerifyButton.addTarget(self, action: #selector(getVerifyCode(_:)), for: .touchUpInside)
        
        emailTextField.addTarget(self, action: #selector(textFieldValueChange(_:)), for: .editingChanged)
        verifyTextField.addTarget(self, action: #selector(textFieldValueChange(_:)), for: .editingChanged)
        emailTextField.delegate = self
        verifyTextField.delegate = self
        button.isEnabled = false
        
        button.addTarget(self, action: #selector(nextStep(_:)), for: .touchUpInside)
        
        self.view.addSubview(closeButton)
        self.view.addSubview(titleLabel)
        self.view.addSubview(descriptionLabel)
        self.view.addSubview(emailTextField)
        self.view.addSubview(emailSaperator)
        self.view.addSubview(verifyTextField)
        self.view.addSubview(verifySaperator)
        self.view.addSubview(getVerifyButton)        
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let touch = touches.first {
            let point = touch.location(in: self.view)
            if !self.emailTextField.frame.contains(point) && !self.verifyTextField.frame.contains(point) {
                self.emailTextField.resignFirstResponder()
                self.verifyTextField.resignFirstResponder()
            }
        }
    }
    
    func showAgreement(_ sender: UIButton) {
        let agreementPage = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "AgreementNavigationController") as! UINavigationController
        self.present(agreementPage, animated: true, completion: nil)
    }
    
    func getVerifyCode(_ sender: UIButton) {
        if Validate.email(emailTextField.text!).isRight {
            //请求验证码
            userAuthVM.getChangePWTotp(email: emailTextField.text!).subscribe(onNext: { json in
                if json is Bool {
                    if !(json as! (Bool)) {
                        self.showPromptView(message: LanguageHelper.getString(key: "ERROR_OCCUR"), confirmText: LanguageHelper.getString(key: "OK"))
                    }
                }
            }, onError: { error in
                print(error)
            })
                .addDisposableTo(disposeBag)
            //冷却按钮
            self.toWaitSec = 60
            self.getVerifyButton.setTitle("\(LanguageHelper.getString(key: "RESENT"))（\(self.toWaitSec)）", for: .disabled)
            self.getVerifyButton.isEnabled = false
            timer = Foundation.Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(waitToGetAgain), userInfo: nil, repeats: true)
        } else {
            self.showPromptView(message: LanguageHelper.getString(key: "INVALID_EMAIL"), confirmText: LanguageHelper.getString(key: "OK"))
        }
    }
    
    func waitToGetAgain() {
        self.toWaitSec -= 1
        if self.toWaitSec == 0 {
            timer.invalidate()
            self.getVerifyButton.isEnabled = true
        } else {
            self.getVerifyButton.setTitle("\(LanguageHelper.getString(key: "RESENT"))（\(self.toWaitSec)）", for: .disabled)
        }
    }
    
    func textFieldValueChange(_ sender: UITextField) {
        if self.emailTextField.text != "" && self.verifyTextField.text != "" {
            self.button.isEnabled  = true
        } else {
            self.button.isEnabled = false
        }
    }
    
    func textFieldDidBeginEditing(_ textField: UITextField) {
        if textField == self.emailTextField {
            emailSaperator.backgroundColor = UIColor.black
        } else {
            verifySaperator.backgroundColor = UIColor.black
        }
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        if textField == self.emailTextField {
            emailSaperator.backgroundColor = saperatorColor
        } else {
            verifySaperator.backgroundColor = saperatorColor
        }
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if textField != verifyTextField {
            return true
        }
        if range.length + range.location > (textField.text?.count)! {
            return false
        }
        let newLength = (textField.text?.count)! + string.count - range.length
        return newLength <= verifyCodeLength
    }
    
    func jumpToLogin(_ sender: UIButton) {
        if let function = self.showLoginView {
            function(self)
        }
    }
    
    func nextStep(_ sender: UIButton) {
        //驗證
        self.emailTextField.resignFirstResponder()
        self.verifyTextField.resignFirstResponder()
        userAuthVM.verifyTOTP(email: self.emailTextField.text!, totp: self.verifyTextField.text!).subscribe(onNext: { result in
            if let con = result.totpValid {
                if con {
                    let changePWView = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "ChangePasswordViewController") as! ChangePasswordViewController
                    changePWView.totpResult = result
                    self.navigationController?.pushViewController(changePWView, animated: true)
                } else {
                    self.showPromptView(message: LanguageHelper.getString(key: "EMAIL_VERIFY_FAIL"), confirmText: LanguageHelper.getString(key: "OK"))
                }
            }
        })
        .addDisposableTo(disposeBag)
    }
    
    func close(_ sender: UIButton) {
        self.dismiss(animated: true, completion: nil)
    }
}
